package com.lhy.order.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lhy.order.entity.Order;
import com.lhy.order.feign.AdminFeign;
import com.lhy.order.feign.VaccineStockFeign;
import com.lhy.order.mapper.OrderMapper;
import com.lhy.order.service.OrderService;
import com.lhy.order.vo.*;
import com.lhy.vaccine_common.vo.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    AdminFeign adminFeign;
    @Autowired
    VaccineStockFeign vaccineStockFeign;

    @Transactional
    @Override
    public R insertOrder(RuleFormVo ruleFormVo) {
        Order order = new Order();

        if (ruleFormVo != null) {
            // 1.查询出省份，城市，县镇的id 并封装
            RegionVo regionVo = null;
            if (!ruleFormVo.getRegion().equals("")) {
                regionVo = orderMapper.getByRegion(ruleFormVo.getCity(),ruleFormVo.getRegion());
            } else {
                regionVo = orderMapper.getByCity(ruleFormVo.getProvince(),ruleFormVo.getCity());
            }
            order.setOProvinceId(regionVo.getProvince());
            order.setOCityId(regionVo.getCity());
            if (!regionVo.getRegion().equals("1")) {
                order.setORegionId(regionVo.getRegion());
            }

            // 2.远程调用，获取疫苗的id,并且只有携带了疫苗信息，才能是预约
            if (!ruleFormVo.getVname().equals("") || !ruleFormVo.getVmsg().equals("")) {
                VaccineOrderVo vaccineOrderVo = new VaccineOrderVo();
                vaccineOrderVo.setVId(Integer.valueOf(ruleFormVo.getVid()));
                vaccineOrderVo.setVMsg(ruleFormVo.getVmsg());
                vaccineOrderVo.setVName(ruleFormVo.getVname());

                order.setOStatus("预约");

                UUID uuid = UUID.randomUUID();
                String str = uuid.toString();
                order.setOId(str);

                // 3. 远程调用用户服务，将用户存储到用户表中
                UserVo userVo = new UserVo();

                userVo.setName(ruleFormVo.getName());
                userVo.setGender(ruleFormVo.getGender().equals("1")? "男":"女");
                userVo.setPhone(ruleFormVo.getPhone());
                userVo.setTelephone(ruleFormVo.getTelephone());
                userVo.setProvince(ruleFormVo.getProvince());

                if (!regionVo.getRegion().equals("1")) {
                    userVo.setCity(ruleFormVo.getCity());
                    userVo.setRegion(ruleFormVo.getRegion());
                }else{
                    userVo.setCity(ruleFormVo.getCity());
                }

                // 4. 远程调用 用户表 表中查看是否有 这个用户的信息，
                R userId = adminFeign.getUser(userVo);
                // 如果用户表中没有该用户信息，但是用户还没注册，可以自动注册且直接预约
                if (userId.get("data").equals("")){
                    R insertUser = adminFeign.insertUser(userVo);
                    if (insertUser.get("data").equals("1")){
                        R userIdToRegister = adminFeign.getUser(userVo);
                        order.setUId((Integer) userIdToRegister.get("data"));

                        R vaccineId = vaccineStockFeign.getVaccineId(vaccineOrderVo);

                        order.setVId(Integer.valueOf(ruleFormVo.getVid()));
                        orderMapper.insertByMyself(order);

                    }else if (insertUser.get("data").equals("0")){
                        return R.error().put("data","0");
                    }
                }else{
                    order.setUId((Integer) userId.get("data"));
                    order.setVId(Integer.valueOf(ruleFormVo.getVid()));
                    // 如果有且疫苗id相同，说明他不能再次预约一样的
                    Order order1 = orderMapper.getByUIdAndVId(order.getUId(),Integer.valueOf(ruleFormVo.getVid()));
                    if (order1 != null){
                        return R.error().put("data","该用户已经预约过这个疫苗");
                    }else {
                        orderMapper.insertByMyself(order);
                    }
                }
            }else {
                return R.ok().put("data","-1");
            }
            return R.ok().put("data","success!");
        }
        return R.error("数据为null");
    }

    @Override
    public R getOrderList(Integer currentPage, Integer pageSize) {

        //1.获取 订单编号 订单状态 订单城市
        int page = (currentPage-1) * pageSize;
        int size = pageSize*currentPage;
        PageVo pageVo1 = orderMapper.selectByMyself();
        List<Order> orders = orderMapper.selectPageByMyself(page, size);
        List<OrderVo> orderVos = null;
        if (orders.size()>0) {
            orderVos = orders.stream().map(order -> {
                OrderVo orderVo = new OrderVo();
                orderVo.setOId(order.getOId());

                // 1.1 远程调用 获取城市名称
                R city = vaccineStockFeign.getCityById(order.getOCityId());
                orderVo.setOCity((String) city.get("data"));

                orderVo.setOStatus(order.getOStatus());

                //2. 获取用户信息 -名字
                R userById = adminFeign.getUserById(order.getUId());
                orderVo.setUName((String) userById.get("data"));

                //3. 获取疫苗信息 -名字
                R vaccineById = vaccineStockFeign.getVaccineById(order.getVId());
                orderVo.setVName((String) vaccineById.get("data"));

                return orderVo;
            }).collect(Collectors.toList());
        }

        PageVo pageVo = new PageVo();
        pageVo.setTotal(pageVo1.getTotal());
        pageVo.setData(orderVos);

        return R.ok().put("data",pageVo);
    }

    @Override
    public R userInsertOrder(RuleFormVo ruleFormVo) {
        R vaccineByName = vaccineStockFeign.getVaccineByName(ruleFormVo.getVname());
        ruleFormVo.setVid(String.valueOf(vaccineByName.get("vid")));
        ruleFormVo.setVmsg((String) vaccineByName.get("vmsg"));

        R r = insertOrder(ruleFormVo);
        return r;
    }

    @Override
    public R getOrderByUserId(String uid) {
        List<Order> orders = orderMapper.getOrderByUserId(uid);
        if (orders.size() > 0){
            List<UserOrderVo> userOrderVos = orders.stream().map(order -> {
                UserOrderVo userOrderVo = new UserOrderVo();

                // 1. 填充 状态
                userOrderVo.setOStatus(order.getOStatus());
                userOrderVo.setTime(order.getOTime());

                // 2. 远程调用用户服务，获取姓名
                R userById = adminFeign.getUserById(order.getUId());
                userOrderVo.setUName((String) userById.get("data"));

                // 3. 远程调用疫苗库存服务，获取名称
                R vaccineById = vaccineStockFeign.getVaccineById(order.getVId());
                userOrderVo.setVName((String) vaccineById.get("data"));

                // 4. 判断用户地址id，远程调用获取名称
                if (!order.getORegionId().equals("")){
                    R cityById = vaccineStockFeign.getCityById(order.getORegionId());
                    userOrderVo.setRegion((String) cityById.get("data"));
                }else {
                    R cityById = vaccineStockFeign.getCityById(order.getOCityId());
                    userOrderVo.setCity((String) cityById.get("data"));
                }

                return userOrderVo;
            }).collect(Collectors.toList());

            if (userOrderVos.size() > 0){
                return R.ok().put("data",userOrderVos);
            }
        }
        return R.error();
    }
}
